package com.ikdong.toodle.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.ikdong.toodle.R;
import com.ikdong.toodle.model.Folder;
import com.ikdong.toodle.model.Goal;
import com.ikdong.toodle.model.Task;
import com.ikdong.toodle.model.TaskContext;
import com.ikdong.toodle.util.ComUtil;
import com.ikdong.toodle.util.Constant;
import com.ikdong.toodle.util.ContextManager;
import com.ikdong.toodle.util.FolderManager;
import com.ikdong.toodle.util.GoalManager;
import com.ikdong.toodle.util.TaskManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

public class TaskAddActivity extends BasicActivity implements View.OnClickListener{
	public static final String OPERATION = "OPERATION";
	public static final Long OP_UPDATE = Long.valueOf(0);
	public static final Long OP_ADD = Long.valueOf(1);
	public static final String TID = "TID";
	private Task task;
	private FolderManager fm;
	private TaskManager tm;
	private ContextManager cm;
	private GoalManager gm;
	private Long operation;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_add);
        
        fm = new FolderManager(this);
        tm = new TaskManager(this);
        cm = new ContextManager(this);
        gm = new GoalManager(this);
        
        operation = this.getIntent().getExtras().getLong(OPERATION);
        task = new Task();
        if(OP_UPDATE.equals(operation)){
            Long taskId = this.getIntent().getExtras().getLong(TID);
            task = tm.get(taskId);
        }else{
            task.setId(new Date().getTime());
            task.setPriority(Long.valueOf(0));
        }

        initView();
        initData();
	}
	
	private void initView(){
		getSupportActionBar().setTitle(getString(R.string.actionbar_title_add_task));
		
		this.findViewById(R.id.ta_task_comp).setOnClickListener(this);
		this.findViewById(R.id.ta_task_star).setOnClickListener(this);
		this.findViewById(R.id.ta_task_status_lst).setOnClickListener(this);
		this.findViewById(R.id.ta_task_prioirty_lst).setOnClickListener(this);
		this.findViewById(R.id.ta_task_folder_lst).setOnClickListener(this);
		this.findViewById(R.id.ta_task_due_lst).setOnClickListener(this);
		this.findViewById(R.id.ta_task_start_lst).setOnClickListener(this);
		this.findViewById(R.id.ta_task_note_lst).setOnClickListener(this);
		
		EditText title = (EditText) this.findViewById(R.id.ta_task_title);
		title.setOnEditorActionListener(new TextView.OnEditorActionListener() {			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				saveTask();
				return false;
			}
		});
	}
	
	private void initData(){
		EditText title = (EditText)findViewById(R.id.ta_task_title);
		if(title.getText().length()==0 && task.getTitle()!=null){
			((EditText)findViewById(R.id.ta_task_title)).setText(task.getTitle());
		}
		if(task.getNote()!=null){
			((TextView)findViewById(R.id.ta_task_note)).setText(task.getNote());
		}
		if(task.getStartdate()!=null && task.getStartdate()>0){			
			((TextView)findViewById(R.id.ta_task_start_date)).setText(ComUtil.formateDate(ComUtil.parseDateByUS(task.getStartdate()), "EEE, d MMM yyyy"));
		}else{
			((TextView)findViewById(R.id.ta_task_start_date)).setText(this.getString(R.string.lable_task_no_date));
		}
		if(task.getDuedate()!=null && task.getDuedate()>0){
			((TextView)findViewById(R.id.ta_task_due_date)).setText(ComUtil.formateDate(ComUtil.parseDateByUS(task.getDuedate()), "EEE, d MMM yyyy"));
		}else{
			((TextView)findViewById(R.id.ta_task_due_date)).setText(this.getString(R.string.lable_task_no_date));
		}
		if(task.getStatus()!=null){
			((TextView)findViewById(R.id.ta_task_status)).setText(task.getStatusFormat());
		}
		if(task.getPriority()!=null){
			((TextView)findViewById(R.id.ta_task_priority)).setText(task.getPriorityFormat());
		}
		if(task.getFolder()!=null && task.getFolder()>0){
			Folder folder = fm.get(task.getFolder());
			((TextView)findViewById(R.id.ta_task_folder)).setText(folder!=null?folder.getName():getString(R.string.lable_task_no_forlder));
		}
		if(Long.valueOf(1).equals(task.getCompleted())){
			((ImageButton)findViewById(R.id.ta_task_comp)).setImageResource(R.drawable.ic_checkbox_full);
		}else{
			((ImageButton)findViewById(R.id.ta_task_comp)).setImageResource(R.drawable.ic_checkbox_empty);
		}
		if(Long.valueOf(1).equals(task.getStar())){
			((ImageButton)findViewById(R.id.ta_task_star)).setImageResource(R.drawable.ic_star_on);
		}else{
			((ImageButton)findViewById(R.id.ta_task_star)).setImageResource(R.drawable.ic_star_off);
		}
		if(task.getStarttime()!=null && task.getStarttime()>0){
			TextView sp = (TextView) this.findViewById(R.id.ta_task_date_sp);
			TextView startTime = (TextView) this.findViewById(R.id.ta_task_start_time);
			sp.setVisibility(View.VISIBLE);
			startTime.setVisibility(View.VISIBLE);
			startTime.setText(task.getTimeFormat(task.getStarttime()));
		}else{
			TextView sp = (TextView) this.findViewById(R.id.ta_task_date_sp);
			TextView startTime = (TextView) this.findViewById(R.id.ta_task_start_time);
			sp.setVisibility(View.GONE);
			startTime.setVisibility(View.GONE);
		}
		if(task.getDuetime()!=null && task.getDuetime()>0){
			TextView dp = (TextView) this.findViewById(R.id.ta_task_date_dp);
			TextView dueTime = (TextView) this.findViewById(R.id.ta_task_due_time);
			dp.setVisibility(View.VISIBLE);
			dueTime.setVisibility(View.VISIBLE);
			dueTime.setText(task.getTimeFormat(task.getDuetime()));
		}else{
			TextView dp = (TextView) this.findViewById(R.id.ta_task_date_dp);
			TextView dueTime = (TextView) this.findViewById(R.id.ta_task_due_time);
			dp.setVisibility(View.GONE);
			dueTime.setVisibility(View.GONE);
		}	
		
		if(OP_UPDATE.equals(operation)){
			if(task.getContext()!=null && task.getContext()>0){
				TaskContext ctx = cm.getContext(task.getContext().longValue());
				if(ctx!=null){
					((TextView)findViewById(R.id.ta_task_context)).setText(ctx.getName());
				}
			}
			if(task.getGoal()!=null && task.getGoal()>0){
				Goal goal = gm.getGoal(task.getGoal().longValue());
				if(goal!=null){
					((TextView)findViewById(R.id.ta_task_goal)).setText(goal.getName());
				}
			}
			if(task.getTag()!=null || task.getTag().trim().length()>0){
				((TextView)findViewById(R.id.ta_task_tag)).setText(task.getTag());
			}
		}
	}


	@Override
	public void onClick(View v) {
		if(R.id.ta_task_status_lst==v.getId()){
			Long[] statusHV = new Long[]{Long.valueOf(0),Long.valueOf(1),Long.valueOf(2),Long.valueOf(3),Long.valueOf(4),Long.valueOf(5),Long.valueOf(6),Long.valueOf(7),Long.valueOf(8),Long.valueOf(9),Long.valueOf(10)};
			String[] statusVV = new String[]{"None","Next Action","Active","Planning","Delegated","Waiting","Hold","Postponed","Someday","Canceled","Reference"};
			showDialog("",task.getStatus(),statusHV, statusVV,task,v.getId());
		}else if(R.id.ta_task_prioirty_lst==v.getId()){
			Long[] priorityHV = new Long[]{Long.valueOf(-1),Long.valueOf(0),Long.valueOf(1),Long.valueOf(2),Long.valueOf(3)};
			String[] priorityVV = new String[]{"Negative","Low","Medium","High","Top"};
			showDialog("",task.getPriority(),priorityHV, priorityVV,task,v.getId());
		}else if(R.id.ta_task_folder_lst==v.getId()){
			List<Folder> folders = fm.get();
			if(folders.size()>0){
				Long[] folderHV = new Long[folders.size()+1];
				String[] folderVV = new String[folders.size()+1];
				folderHV[0] = Long.valueOf(0);
				folderVV[0] = "None";
				for(int i=0; i<folders.size(); i++){
					folderHV[i+1] = folders.get(i).getId();
					folderVV[i+1] = folders.get(i).getName();
				}
				
				showDialog("",task.getFolder(),folderHV, folderVV,task,v.getId());
			}else{
				showToast("There is no folder.");
			}
		}else if(R.id.ta_task_due_lst==v.getId()){
			Intent intent = new Intent(this,TaskAddDateSetActivity.class);
			intent.putExtra(TaskAddDateSetActivity.PARAM_OPERATION, TaskAddDateSetActivity.SET_DUE);
			intent.putExtra(TaskAddDateSetActivity.PARAM_DATE, task.getDuedate()!=null?task.getDuedate():0);
			intent.putExtra(TaskAddDateSetActivity.PARAM_TIME, task.getDuetime()!=null?task.getDuetime():0);
			this.startActivityForResult(intent, TaskAddDateSetActivity.SET_DUE);			
		}else if(R.id.ta_task_start_lst==v.getId()){
			Intent intent = new Intent(this,TaskAddDateSetActivity.class);
			intent.putExtra(TaskAddDateSetActivity.PARAM_OPERATION, TaskAddDateSetActivity.SET_START);
			intent.putExtra(TaskAddDateSetActivity.PARAM_DATE, task.getStartdate()!=null?task.getStartdate():0);
			intent.putExtra(TaskAddDateSetActivity.PARAM_TIME, task.getStarttime()!=null?task.getStarttime():0);
			this.startActivityForResult(intent, TaskAddDateSetActivity.SET_START);			
		}else if(R.id.ta_task_note_lst==v.getId()){
			this.showNoteDailoag(task.getNote());
		}else if(R.id.ta_task_comp==v.getId()){
			task.setCompleted(task.getCompleted()!=null&&task.getCompleted()==0 ? Long.valueOf(1):Long.valueOf(0));
			initData();
		}else if(R.id.ta_task_star==v.getId()){
			task.setStar(task.getStar()!=null&&task.getStar()==0 ? Long.valueOf(1):Long.valueOf(0));
			initData();
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportActionBar().setTitle(getString(R.string.actionbar_title_add_task));
		
		MenuItem cancelItem = menu.add(getString(R.string.lable_action_cancel));
		cancelItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		cancelItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				setResult(-1, null);
				finish();
				return true;
			}});
		
		if(OP_UPDATE.equals(operation)){
			MenuItem deleteItem = menu.add(getString(R.string.lable_action_delete));
			deleteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
			deleteItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
				@Override
				public boolean onMenuItemClick(MenuItem item) {
					new AlertDialog.Builder(TaskAddActivity.this)
				    	.setTitle(getString(R.string.msg_alert_task_delete_title))
				    	.setMessage(getString(R.string.msg_alert_task_delete_body))
				    	.setPositiveButton(getString(R.string.lable_action_ok), new DialogInterface.OnClickListener() {
				    		public void onClick(DialogInterface dialog, int which) { 
				    			tm.delete(task.getId());			
								setResult(OP_UPDATE.intValue(), null);
								finish();	
				    		}
				    	})
				    	.setNegativeButton(getString(R.string.lable_action_cancel), new DialogInterface.OnClickListener() {
				    		public void onClick(DialogInterface dialog, int which) {}
				    	})
				    	.show();
									
					return true;
					
				}});
		}
		
		MenuItem saveItem = menu.add(getString(R.string.lable_action_save));
		saveItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		saveItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				saveTask();				
				return true;
				
			}});
		
		return true;
	}
	
	private void saveTask(){
		EditText title = (EditText) findViewById(R.id.ta_task_title);
		if(title.getText()==null || title.getText().length()==0){
			showToast(TaskAddActivity.this.getString(R.string.msg_task_name_error));
		}else{
			task.setTitle(title.getText().toString());
			if(OP_UPDATE.equals(operation)){
				tm.update(task);
			}else{
				tm.add(task);
				List<Task> tasks = new ArrayList<Task>();
				tasks.add(task);
			}
		}				
		setResult(OP_UPDATE.intValue(), null);
		finish();		
	}
	
	@Override
	void refresh() {
		
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode==TaskAddDateSetActivity.SET_START && data!=null){
			task.setStartdate(data.getLongExtra(TaskAddDateSetActivity.PARAM_DATE, 0));
			Log.d(Constant.TAG, "get time: "+data.getLongExtra(TaskAddDateSetActivity.PARAM_TIME, 0));
			task.setStarttime(data.getLongExtra(TaskAddDateSetActivity.PARAM_TIME, 0));
			initData();
		}else if(resultCode==TaskAddDateSetActivity.SET_DUE && data!=null){
			task.setDuedate(data.getLongExtra(TaskAddDateSetActivity.PARAM_DATE, 0));
			task.setDuetime(data.getLongExtra(TaskAddDateSetActivity.PARAM_TIME, 0));
			initData();
		}
	}
	
	int selectedItem = -1;
	private void showDialog(String title,Long value,final Long[] hValues, String[] vValues, final Task task, final int id){		
		selectedItem = -1;
		for(int i=0; i<hValues.length; i++){
			if(hValues[i].equals(value)){
				selectedItem = i;
				break;
			}
		}
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(TaskAddActivity.this);
		dialog.setTitle(title);		
		dialog.setSingleChoiceItems(vValues, selectedItem,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						selectedItem = whichButton;
					}
				})
				.setPositiveButton(TaskAddActivity.this.getString(R.string.lable_action_save), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Long value = hValues[selectedItem];
						if(R.id.ta_task_status_lst==id){
							task.setStatus(value);
						}else if(R.id.ta_task_prioirty_lst==id){
							task.setPriority(value);
						}else if(R.id.ta_task_goal_lst==id){
							task.setGoal(value);
						}else if(R.id.ta_task_folder_lst==id){
							task.setFolder(value);
						}else if(R.id.ta_task_location_lst==id){
							task.setLocation(value);
						}else if(R.id.ta_task_context_lst==id){
							task.setContext(value);
						}else if(R.id.ta_task_folder_lst==id){
							task.setFolder(value);
						}
						
						initData();
					}
				})
				.setNegativeButton(TaskAddActivity.this.getString(R.string.lable_action_cancel),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int whichButton) {
							}
						});	
		dialog.show();
	}
	
	private void showNoteDailoag(String value){
		final FrameLayout fl = new FrameLayout(TaskAddActivity.this);
		final EditText input = new EditText(TaskAddActivity.this);
		input.setSingleLine(false);
		input.setLines(8);
		input.setGravity(Gravity.TOP);
		if(task.getNote()!=null)
			input.setText(value);
		fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
		
		AlertDialog.Builder builder = new AlertDialog.Builder(TaskAddActivity.this);
		builder.setView(fl).setTitle(this.getString(R.string.lable_task_note)).
			setPositiveButton(this.getString(R.string.lable_action_ok), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {    
        			task.setNote(input.getText().toString());
        			initData();
                }
		    }).
		    setNegativeButton(this.getString(R.string.lable_action_cancel), new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		builder.create().show();
	}
}
